import Vue from "vue";
import VueRouter from "vue-router";
import Layout from "../views/Layout.vue";
import Login from "../views/Login.vue";
import NProgress from "nprogress"
import "nprogress/nprogress.css"
Vue.use(VueRouter);

//解决同一个路径只能点击一次的问题
const originPush = VueRouter.prototype.push;
VueRouter.prototype.push = function (loaction) {
  originPush.call(this, loaction).catch(() => {});
};

const routes = [
  { path: "/", redirect: "/login" },
  {
    name:"首页",
    path: "/layout",
    component: Layout,
    meta:{
      icon:"el-icon-s-shop",
      name:"首页"
    }
  },
  {
    path: "/login",
    name: "Login",
    component: Login,
    children:[

    ]
  },
];


const router = new VueRouter({
  mode: "history",
  base: process.env.BASE_URL,
  routes,
});
//--------- 动态路由----------
const oMenus = JSON.parse(localStorage.getItem("data") || "{}").manu;
const formatMenus = (data=[], pid = 0) => {
  function tree(pid) {
    let arr = [];
    data
      .filter((item) =>{
        return item.parentid == pid
      })
      .forEach((item) => {
        const obj = {
          name: item.menuname,
          path:  "/layout"+ item.url,
          menuid: item.menuid,
          meta: {
            icon: item.icon ,
            name:item.name
          },
        
          component: () => import(`../views/module${item.url}.vue`),
          children: tree(item.menuid),
        };
        arr.push(obj);
        if (obj.path != "/") {
          router.addRoute("首页", { ...obj });
        }
      });

    return arr;
  }
  return tree(pid);
};
formatMenus(oMenus);

//前置守卫
router.beforeEach((to,from,next)=>{
  NProgress.start()
  if (to.path == '/login') {
    return next()
  }

  const token = localStorage.getItem('token')

  //备用
  const token1=sessionStorage.getItem("token")

  if (!token) {
    return next('/login')
  }

  return next()
})
//全局的后置守卫
router.afterEach(() => {
  NProgress.done()
  // next()
})

export default router;
